$(function(){
	genresite_index.run();
});

var genresite_index = {
	run: function(){
		this._init_();
		this._start_();
		this._init_events();
	},
	
	_init_: function(){		
	},
	
	_start_: function(){
	},
	
	_init_events: function(){
		$("#add_genresite_btn").click(function(){				
			$("#new_genresite_div").admindialog('open');
			$("#genreCategory").change(function(){
				var category = $(this).val();
				genresite_index._handle_category_change(category,"genreId");
			});
		});
		
		genresite_index._handle_update_delete_event();
	},
	
	_handle_update_delete_event: function(){
		//ready for dialog
		$("#new_genresite_div").admindialog({
			offsetLeft: -20,
			offsetTop: -50,
			gatherData: true,
			submit: function(data){
				var url = main.contextPath + "/admin/sitegenre/add";
				$.post(url, data, function(result){
					location.reload(location.href);
				});
			}
		});
		
		//ready for dialog
		$("#update_genresite_div").admindialog({
			gatherData: true,
			submit: function(data){
				var url = main.contextPath + "/admin/sitegenre/update";
				$.post(url, data, function(result){
					location.reload(location.href);
				});					
			}
		});
		
		$("#genresite_table  tr > td > a.update").click(function(){
			var id = $(this).attr("linkId");
			var url = main.contextPath + "/admin/sitegenre/get/" + id;
			$.get(url, function(result){
				$("#update_content_div").html(result);
				var category = $("#updateGenreCategory").val();
				genresite_index._handle_category_change(category, "updateGenreId");
				$("#updateGenreCategory").change(function(){
					var category = $(this).val();
					genresite_index._handle_category_change(category,"updateGenreId");
				});
				$("#update_genresite_div").dialog('open');
			});
		});
		
		$("#genresite_table  tr > td > a.delete").click(function(){
			var checked = window.confirm("Are you sure ?");
			if(checked){
				var id = $(this).attr("linkId");
				var url = main.contextPath + "/admin/sitegenre/delete/" + id;
				$.get(url, function(result){
					alert(result);
					location.reload(location.href);
				});
			}				
		});
	},
	
	_handle_category_change: function(category,id){
		var url = main.contextPath + "/admin/sitegenre/getGenres?category=" + category;
		var genreID = $("#genreID").val();
		$.get(url, function(result){
			var json = eval('(' + result + ')');
			$("#" + id).html("");
			$.each(json,function (index, domEle) {
				if(id == "updateGenreId" && genreID == domEle.id){
					$("#" + id).append("<option selected='true' value="+ domEle.id +">" + domEle.genreName + "</option>");
				}else{
					$("#" + id).append("<option value="+ domEle.id +">" + domEle.genreName + "</option>");
				}
			});
		});
	}
};